﻿

@namespace ThingsGateway.Admin.Blazor
@using Microsoft.AspNetCore.SignalR.Client;
@using System.Security.Claims;
@using ThingsGateway.Admin.Application;
@implements IAsyncDisposable;
@code {
    HubConnection _hubConnection;

    [Inject]
    IPopupService PopupService { get; set; }

    /// <inheritdoc/>
    public async ValueTask DisposeAsync()
    {
        if (_hubConnection != null)
        {
            await _hubConnection.DisposeAsync();
        }
    }
    [Inject]
    NavigationManager NavigationManager { get; set; }

    /// <inheritdoc/>
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            try
            {
                //SignalR
                _hubConnection = new HubConnectionBuilder().WithUrl(NavigationManager.ToAbsoluteUri(HubConst.SysHubUrl), (opts) =>
            {
                opts.HttpMessageHandlerFactory = (message) =>
                {
                    if (message is HttpClientHandler clientHandler)
                    {
                        // 绕过SSL证书
                        clientHandler.ServerCertificateCustomValidationCallback += (sender, certificate, chain, sslPolicyErrors) =>
                        {
                            return true;
                        };
                    };
                    return message;
                };
                foreach (var item in App.User?.Claims ?? new List<Claim>())
                {
                    if (item.Type == ClaimConst.UserId || item.Type == ClaimConst.VerificatId)
                        opts.Headers.Add(item.Type, item.Value);
                }
            }
            ).Build();

                _hubConnection.On<string>(nameof(ISysHub.LoginOut), async (message) =>
                {
                    await InvokeAsync(async () => await PopupService.EnqueueSnackbarAsync(new(message, AlertTypes.Warning)));
                    await Task.Delay(2000);
                    NavigationManager.NavigateTo(NavigationManager.Uri, true);
                });
                _hubConnection.On<SignalRMessage>(nameof(ISysHub.NewMessage), async (message) =>
                {
                    await InvokeAsync(async () => await PopupService.EnqueueSnackbarAsync(new(message?.Data, (byte)message.LogLevel <= 2 ? AlertTypes.Success : AlertTypes.Warning)));
                    await Task.Delay(2000);
                    NavigationManager.NavigateTo(NavigationManager.Uri, true);
                });
                await _hubConnection.StartAsync();
            }
            catch
            {

            }
            await base.OnAfterRenderAsync(firstRender);
        }
    }
}